let express = require('express');
let router = express.Router();
const querystring = require('querystring')
//————————————连接数据库——————————
var mysql = require('mysql');
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'bookshop'
});

connection.connect((err) => {
    if (err) {
        console.log(err)
    }

});

router.post('/', function (req, res, next) {
    // Handle file upload
    let obj = null,
        data = {
            code: 0,
            msg: '请求成功',
            data: {}
        }
    var currentData = ''

    req.on('data', (chunk) => {
        currentData += chunk
    })

    req.on('end', () => {
        obj = querystring.parse(currentData)
        

        console.info('==post obj==', obj)
        console.log(obj.name)
        let name = obj.name;
        let pwd = obj.pass;
        let contact = obj.contact;
        let geneder = obj.geneder;
        let mail = obj.mail;
        
        connection.query("SELECT * FROM update_info WHERE user = '" + name + "'", function (err, ress, fields) {

        let uName = ress[0]

        if (uName == undefined) {
            //    不存在时插入数据
            connection.query('INSERT INTO update_info SET  ?', { user: name, passwork: pwd, contact: contact, geneder: geneder, mail: mail}, function (err, data) {
                if (err) {
                    console.log(err)
                    res.send({ statusCode: 0, msg: '更新失败，请重试' })
                    return
                } else {
                    req.session.token = name
                    res.send({ statusCode: 200, msg: '更新成功' })
                    return
                }
            })
        } else {

            res.send({ code: 0, msg: '用户名已存在' })
        }
    })
        // res.writeHead(200, {
        //     "Content-Type": "text/html;charset=utf-8"
        // })
        // res.end(JSON.stringify(data))
    })
    // console.log(req.file); // Information about the uploaded file
    // res.send('File uploaded successfully!');
  });
module.exports = router;
